<template>
    <div class="body1">
        <div class="no-print el-button-print">
            <el-button @click="addForm">添加页</el-button>
            <el-button @click="deleteForm">删除页</el-button>
            <el-button @click="exportPDF">导出为pdf</el-button>
        </div>
        <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
            <div v-for="(item, index) in form" :key="index" :class="{ 'page-break': index !== 0 }">
                <div class="title">
                    <div class="biaotididian">卷内文件目录</div>
                </div>
                <table class="tableStyle">
                    <colgroup>
                        <col width="7%">
                        <col width="25%">
                        <col width="25%">
                        <col width="23%">
                        <col width="7%">
                        <col width="13%">
                    </colgroup>
                    <thead>
                        <tr>
                            <th style="height: 40px">序号</th>
                            <th>题名</th>
                            <th>文号</th>
                            <th>日期</th>
                            <th>页号</th>
                            <th>备注</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item1, index1) in item" :key="index1">
                            <td style="height: 80px">
                                <el-input v-model="item1.number" :resize="'none'" autosize maxlength="6"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td style="height: 75px">
                                <el-input v-model="item1.name" :resize="'none'" autosize maxlength="24"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td style="height: 75px">
                                <el-input v-model="item1.writNumber" :resize="'none'" autosize maxlength="24"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td style="height: 75px">
                                <editable-textarea :text="item1.date" param-type="YYYYMMDD"
                                    @send-to-parent="(data, type) => receiveFromChild(data, type, index, index1)"></editable-textarea>
                            </td>
                            <td style="height: 75px">
                                <el-input v-model="item1.page" :resize="'none'" autosize maxlength="6"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                            <td style="height: 75px">
                                <el-input v-model="item1.remark" :resize="'none'" autosize maxlength="12"
                                    class="areaInputStyle" type="textarea" ref="inputRef6">
                                </el-input>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</template>
<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js";

export default {
    components: {
        EditableTextarea
    },
    data() {
        return {
            form: [
                [
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                    // { number: '', name: '', writNumber: '', date: '', page: '', remark: '' },
                ]
            ],
            dialogFormVisible: false,
            isPdfExport: false, // 控制打印样式
            paramName: '',
            paramtype: '',
        }
    },
    mounted() {
        window.parent.changeTemplateDow();
    },
    created() {
        window.parent.getTemplateData((data) => {
            // 检查数据是否为数组，不是则使用默认值
            this.form = Array.isArray(data) ? data : [
                Array(10).fill().map(() => ({
                    number: '', name: '', writNumber: '', date: '', page: '', remark: ''
                }))
            ];
        });
        //将方法暴露在初始化加载中
        window.postForm = () => {
            this.postForm();
        }
    },
    methods: {
        addForm() {
            if (!Array.isArray(this.form)) {
                this.form = []; // 重置为数组
            }
            // 添加新页（包含12个空行）
            this.form.push(Array(10).fill().map(() => ({
                number: '', name: '', writNumber: '', date: '', page: '', remark: ''
            })));
        },
        deleteForm() {
            // 确保至少保留一页
            if (this.form.length > 1) {
                this.form.pop();
            } else {
                // 使用Element UI的提示（确保已引入ElMessage）
                this.$message.warning('至少需要保留一页');
            }
        },
        // 导出为pdf
        exportPDF() {
            this.savePDF()
                .then((blob) => {
                    const blobUrl = URL.createObjectURL(blob);

                    // 先预览
                    const previewWindow = window.open(blobUrl, '_blank');

                    // 自动下载
                    const fileName = `卷内文件目录.pdf`;
                    const downloadLink = document.createElement('a');
                    downloadLink.href = blobUrl;
                    downloadLink.download = fileName;
                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);

                    // 监听预览窗口关闭后释放内存
                    if (previewWindow) {
                        const timer = setInterval(() => {
                            if (previewWindow.closed) {
                                clearInterval(timer);
                                URL.revokeObjectURL(blobUrl);
                            }
                        }, 1000);
                    } else {
                        setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
                    }
                })
                .catch(error => {
                    console.error('导出PDF出错:', error);
                    alert('导出失败，请重试或联系管理员');
                });
        },
        savePDF() {
            this.isPdfExport = true; // 激活PDF样式
            return new Promise((resolve, reject) => {
                this.$nextTick(() => {
                    import('html2pdf.js').then((module) => {
                        const html2pdf = module.default;

                        //获取所有需要替换的 el-input
                        const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

                        //存储原始元素和它们的父节点，方便后续恢复
                        const originalElements = [];

                        elInputs.forEach((input) => {
                            const div = document.createElement('div');
                            div.style.whiteSpace = 'pre-wrap'; // 保留换行
                            div.style.fontFamily = '仿宋';
                            div.style.fontSize = '5mm';
                            div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
                            div.style.lineHeight = '1.3';

                            // 替换 el-input，并存储原始元素
                            originalElements.push({
                                parent: input.parentNode,
                                original: input,
                                replacement: div,
                            });
                            input.parentNode.replaceChild(div, input);
                        });

                        // 配置选项
                        const opt = {
                            margin: 0,
                            image: {
                                type: 'jpeg',
                                quality: 0.98
                            },
                            html2canvas: {
                                scale: 2,
                                logging: false,
                                useCORS: true
                            },
                            jsPDF: {
                                unit: 'mm',
                                format: 'a4',
                                orientation: 'portrait'
                            }
                        };

                        const element = document.getElementById('pdfDom');

                        // 生成PDF Blob对象
                        html2pdf()
                            .set(opt)
                            .from(element)
                            .toPdf()
                            .get('pdf')
                            .then((pdf) => {
                                const blob = pdf.output('blob');

                                resolve(blob); // 返回Blob对象
                            })
                            .catch((error) => {
                                reject(error);
                            })
                            .finally(() => {
                                this.isPdfExport = false; // 恢复原始样式
                                // 恢复原始input
                                originalElements.forEach(({ parent, original, replacement }) => {
                                    parent.replaceChild(original, replacement);
                                });
                            });
                    }).catch((error) => {
                        reject(error);
                        this.isPdfExport = false;
                        originalElements.forEach(({ parent, original, replacement }) => {
                            parent.replaceChild(original, replacement);
                        });
                    });
                });
            });
        },
        //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
        postForm() {
            this.savePDF()
                .then((blob) => {


                    // 创建FormData并添加文件
                    const formData = new FormData();
                    formData.append('file', blob, '卷内文件目录.pdf');

                    window.parent.postTemplateDate(this.form, formData);
                })
                .catch(error => {
                    console.error('整个保存PDF出错:', error);
                });
        },
        //选择日期时间
        receiveFromChild(data, type, index, index1) {
            const TypeMap = {
                'YYYYMMDD': 'date',
            };
            if (TypeMap[type] && this.form[index][index1]) {
                this.form[index][index1][TypeMap[type]] = data;
            }
        },
    },
};
</script>

<style scoped>
:deep(.el-button-print .el-button) {
    display: inline-flex !important;
    visibility: visible !important;
    opacity: 1 !important;
    width: auto;
    min-width: 100px;
    height: auto;
    padding: 8px 15px;
    background: #fff !important;
    color: #000 !important;
    border: none;
}

:deep(.el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 5mm;
    overflow-y: hidden;
    line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 5mm;
    overflow-y: hidden !important;
    resize: none !important;
    height: auto !important;
}

.input-container {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
}

.inputStyleNoLine {
    border: none;
    outline: none;
    padding: 0px;
}

.typeSpan {
    cursor: pointer;
    font-size: 5mm;
}
</style>
